<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>促销商品广告管理</title>
    <link rel="stylesheet" href="/static/lib/layui-v2.5.6/layui-v2.5.6/layui/css/layui.css">
    <style>
        .layui-table-cell{
            height:60px !important;
            line-height: 60px !important;
        }
        .btn-box {
            position: relative;
        }

        .file-ipt {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0; 
        }
        .layui-icon-search{
            font-size: 30px;
            color: #009688;
            cursor: pointer;
            margin-left: 40px;
        }
        .layui-icon{
            cursor: pointer;
        }
        .btn {
            width: 100px;
            height: 30px;
            background-color: skyblue;
            color: white;
            margin-right: 80px;
            border: none;
            border-radius: 10px;
        }
    </style>
</head>
<body>
    <table id="demo" lay-filter="test"></table>


    
    <div id="advertisementUpdate" style="display: none;margin-top: 30px;">
        <form class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">广告名称</label>
                <div class="layui-input-inline">
                    <input id="advertisement_name" type="text" name="advertisement_name" required lay-verify="required" placeholder="请输入广告名" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">广告对应商品ID</label>
                <div class="layui-input-inline">
                    <input id="commodity_id" type="text" name="commodity_id" required lay-verify="required" placeholder="请输入商品ID" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item btn-box" style="margin: 30px 0 0 30px;">
                <button class="btn">上传图片</button>
                <input type="file" id="imgPath" class="file-ipt">
            </div>
            <i style="margin-left: 25px;color: rgb(250, 75, 75);font-size: 12px;">*图片尺寸为：750*300，或此比例*</i>
        </form>
    </div>

    <script type="text/html" id="barDemo">
        <i class="layui-icon layui-icon-list" lay-event="goodsAdvertisementUpdate" title="商品广告详细"></i>
        <i class="layui-icon layui-icon-delete" lay-event="goodsAdvertisementDel" title="广告删除"></i>
        <i class="layui-icon layui-icon-upload-circle" lay-event="goodsAdvertisementDelStatus" title="广告状态改变"></i>
    </script>

    <script type="text/html" id="toolbarDemo">

        <div class="layui-inline" style="width: 150px;">
            <select name="addAdverStatus_2" lay-verify="" id="addAdverStatus_2">
                <option value="">广告状态</option>
                <option value="0">正常</option>
                <option value="1">未上架</option>
            </select>
        </div>
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 150px;">
              <input type="text" name="addAdverName_2" id="addAdverName_2" placeholder="输入广告名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <i class="layui-icon layui-icon-search" lay-event="itemlistSearch_2" title="搜索刷新"></i>
        </div>


        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm layui-btn-radius" lay-event="goodsAdvertisementAdd" style="margin-top:8px">添加广告</button>
        </div>
    </script>

    <script src="/static/lib/layui-v2.5.6/layui-v2.5.6/layui/layui.js"></script>
    
    <script>
        layui.use('table', function(){
            var $ = layui.jquery;
            var table = layui.table;
            // var util = layui.util;


            table.render({
                elem: '#demo',
                height: 'full-15',
                //TODO:
                url: '/admin/saleAdvertisement/query', //数据接口
                page: {layout: ['prev', 'page', 'next', 'skip', 'count']}, //开启分页
                limit: 6,
                toolbar: '#toolbarDemo',
                defaultToolbar: [],
                id: 'goodsaATest',
                cols: [[ //表头
                {field: 'id', title: 'id', width:'5%', sort: true, fixed: 'left'},
                {field: 'advertisement_name', title: '广告名称', width:'15%', sort: true,},
                {field: 'picture_url', title: '广告图片', width:'20%',  templet:'<div><img src="https://vm.fowotek.com{{d.picture_url}}" </div>'},
                {field: 'create_time', title: '创建时间', templet:"<div>{{layui.util.toDateString(Number(d.create_time), 'yyyy.MM.dd HH:mm:ss')}}</div>", width:'15%'} ,
                {field: 'update_time', title: '更新时间', templet:  "<div>{{layui.util.toDateString(Number(d.update_time), 'yyyy.MM.dd HH:mm:ss')}}</div>", width:'15%', sort: true},
                {field: 'commodity_id', title: '广告对应商品ID',},
                {field: 'status', title: '广告状态', width: '10%', templet:'<div>{{adStatus(d.status)}}</div>', sort: true},
                {fixed: 'right', width:'10%', title: '操作', align:'center', toolbar: '#barDemo'}
                ]],


                parseData: function(res){ //res 即为原始返回的数据
                console.log(res)
                    return {
                    "code": res.success, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                    };
                },
                // request: {
                //     pageName: 'curr' //页码的参数名称，默认：page
                //     ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
                // },
                response: {
                    // statusName: 'success', //规定数据状态的字段名称，默认：code
                    statusCode: true //规定成功的状态码，默认：0
                }
            });
        
            table.on('toolbar(test)', function(obj){
                sessionStorage.setItem("addAdverStatus_2_1", $("#addAdverStatus_2").val());
                sessionStorage.setItem("addAdverName_2_1", $("#addAdverName_2").val());
                switch(obj.event){
                    case 'goodsAdvertisementAdd':   
                        $("#imgPath").val('')
                        $("#advertisement_name").val('')
                        $("#commodity_id").val('')
                        layer.open({
                            type: 1,
                            area: ['500px', '350px'], //宽高
                            title: '广告信息添加',
                            btn: ['添加','取消'],
                            content: $('#advertisementUpdate'),
                            yes: function(index){
                                // console.log($("#advertisement_name").val())
                                // var advertisement_name = $("#advertisement_name").val()
                                var file = $("#imgPath")[0].files[0];//获取文件
                                var formData = new FormData();
                                if ($("#advertisement_name").val() == '') {
                                    layer.msg('未填写广告名称')
                                }else if ($("#commodity_id").val() == '') {
                                    layer.msg('未填写商品ID')
                                }else if (file == undefined) {
                                    layer.msg('选择上传图片')
                                }else {
                                    formData.append("picture", file);
                                    formData.append("advertisement_name", $("#advertisement_name").val());
                                    formData.append("commodity_id", $("#commodity_id").val());
                                    $.ajax({
                                        type: "post",
                                        //TODO:
                                        url: "/admin/saleAdvertisement/addAdvertisement",
                                        data: formData,
                                        dataType: "json",
                                        processData: false,
                                        contentType: false,
                                        success: function(mag){
                                            layer.msg(mag.message)
                                            table.reload('goodsaATest')
                                        }
                                    })
                                    layer.close(index);
                                }
                                
                            }
                        });
                    break;

                    
                    case 'itemlistSearch_2':
                    var status = $("#addAdverStatus_2").val()
                    var advertisement_name = $("#addAdverName_2").val()
                    
                    
                    table.reload('goodsaATest', {
                        where: { //设定异步数据接口的额外参数，任意设
                            status: $("#addAdverStatus_2").val() || undefined,
                            advertisement_name: $("#addAdverName_2").val() || undefined
                        },
                        done: function(res, curr, count){
                            this.where={};
                        },
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                    });

                    if (sessionStorage.getItem("addAdverStatus_2_1") == '') {
                        $("#addAdverStatus_2").attr('text','商品状态')
                    }else if(sessionStorage.getItem("addAdverStatus_2_1") == '0'){
                        $("#addAdverStatus_2 option[value= '0']").attr("selected", true);
                    }else if (sessionStorage.getItem("addAdverStatus_2_1") == '1') {
                        $("#addAdverStatus_2 option[value= '1']").attr("selected", true);
                    }

                    if (sessionStorage.getItem("addAdverName_2_1") == '') {
                        $("#addAdverName_2").attr('placeholder','输入广告名')
                    }else{
                        $("#addAdverName_2").attr('placeholder',sessionStorage.getItem("addAdverName_2_1"))
                    }
                    
                    break;
                };
            });

            table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                if(layEvent === 'goodsAdvertisementUpdate'){
                    $("#imgPath").val('')
                    $("#advertisement_name").val('')
                    $("#commodity_id").val('')
                    layer.open({
                        type: 1,
                        area: ['500px', '350px'], //宽高
                        title: '广告信息修改',
                        btn: ['更新','取消'],
                        content: $('#advertisementUpdate'),
                        yes: function(index){
                            var file = $("#imgPath")[0].files[0];//获取文件
                            var formData = new FormData();
                            if ($("#advertisement_name").val() == '') {
                                layer.msg('未填写广告名称')
                            }else if ($("#commodity_id").val() == '') {
                                layer.msg('未填写商品ID')
                            }else {
                                formData.append("picture", file);
                                formData.append("advertisement_name", $("#advertisement_name").val());
                                formData.append("commodity_id", $("#commodity_id").val());
                            
                                $.ajax({
                                    type: "post",
                                    //TODO:
                                    url: "/admin/saleAdvertisement/updateAdvertisement?advertisementId=" +data.id,
                                    data: formData,
                                    dataType: "json",
                                    processData: false,
                                    contentType: false,
                                    success: function(mag){
                                        layer.msg(mag.message)
                                        table.reload('goodsaATest')
                                    }
                                })
                                layer.close(index);
                            }
                        }
                    });
                } else if(layEvent === 'goodsAdvertisementDel'){ //删除
                    layer.confirm('真的删除行么', function(index){
                        $.ajax({
                            type: "post",
                            //TODO:
                            url: "/admin/saleAdvertisement/deleteAdvertisement",
                            data: {advertisementId: data.id},
                            dataType: "json",
                            success: function(mag){
                                layer.msg(mag.message)
                                if (mag.success == true) {
                                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                                    table.reload('goodsaATest')
                                    layer.close(index);
                                }
                            }
                        })
                        
                    });
                } else if(layEvent === 'goodsAdvertisementDelStatus'){ //编辑
                    if (data.status == 0) {
                        layer.confirm('下架该广告', function(index){
                            $.ajax({
                                type: "post",
                                url: "/admin/saleAdvertisement/changeShelf",
                                data: {advertisementId: data.id,action: 'stop'},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            status: '1'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }else {
                        layer.confirm('上架该广告', function(index){
                            $.ajax({
                                type: "post",
                //TODO:
                                url: "/admin/saleAdvertisement/changeShelf",
                                data: {advertisementId: data.id,action: 'start'},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            status: '0'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }
                    
                }
            });


        });
        function adStatus(num) {
            if (num == 0) {
                var status = '正常'
            }else {
                var status = '<span style="color: rgb(222, 130, 235);">未上架</span>'
            }
            return status
        }

        function MillisecondToDate(msd) {
            
            var time = parseFloat(msd) / 1000;   //先将毫秒转化成秒
            if (msd == null || msd == undefined || msd == 0) {
                time = 0
            }else  {
                // time = parseInt(time / 86400) +"天" + parseInt((parseFloat(time / 86400.0) -parseInt(time / 86400.0)) * 60) + "小时" + parseInt((parseFloat((parseFloat(time / 86400.0) - parseInt(time / 86400.0)) * 60) - parseInt((parseFloat(time / 86400.0) - parseInt(time / 86400.0)) * 60)) * 60) + "分钟" + time + "秒";
                var days,hours,minutes,seconds, timesFormat = parseFloat(time / 86400.0);
                days = parseInt(time / 86400);
                hours = parseInt((timesFormat -days) * 60);
                minutes = parseInt((parseFloat((timesFormat - days) * 60) - hours) * 60);
                seconds = parseInt(parseFloat(((parseFloat((timesFormat - days) * 60) - hours) * 60) - minutes) * 60);

                time = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
            }
            return time; 
        }
    </script>
</body>
</html>